//
//  KqImageTool.m
//  kq_flutter_widgets
//
//  Created by wtb on 2023/4/7.
//

#import "KqImageTool.h"

@implementation KqImageTool

//压缩图片
+(NSData *)kqQualityCompressData:(NSData *)imageData{
    UIImage *img = [UIImage imageWithData:imageData];
    return [KqImageTool kqQualityCompressImage:img];
}

//压缩图片
+(NSData *)kqQualityCompressImage:(UIImage *)img{
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(img, compression);
    float imgW = [UIScreen mainScreen].bounds.size.width;
    float imgH = [UIScreen mainScreen].bounds.size.height;
    NSUInteger maxLength = imgW*imgH*0.8;
    
    if (data.length < maxLength) return data;

    CGFloat max = 1;
    CGFloat min = 0;
    
    //进行6次压缩
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(img, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    if (data.length < maxLength) return data;
    UIImage *resultImage = [UIImage imageWithData:data];
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        //GFLog(@"Ratio = %.1f", ratio);
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    return data;
}

//获取图片格式
+ (NSString *)kqImageTypeWithData:(NSData *)data{
    uint8_t type;
    [data getBytes:&type length:1];
    switch (type) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
        case 0x52:
            // R as RIFF for WEBP
            if ([data length] < 12) {
                return nil;
            }
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return nil;
    }
    return nil;
}
@end
